Skip to content

fix(provider): bound Gemma-4 checkpoint-capture to stop the Metal live-resource (499000) leak - #374

Merged
Gajesh2007 merged 3 commits into
masterfrom
fix/gemma4-checkpoint-capture-leak
Jun 16, 2026
Merged

Gajesh2007 merged 3 commits into
masterfrom
fix/gemma4-checkpoint-capture-leak

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Jun 16, 2026 •

Copy link
Copy Markdown
Member

Summary

Gemma-4 (gemma-4-26b-qat-4bit) crash-loops on busy providers with
[metal::malloc] Resource limit (499000) exceeded (≈ every 15 min on an M3
Ultra with free RAM). This is a live Metal buffer-COUNT leak, not a
bytes/cache problem. This PR bounds the checkpoint KV-capture pipeline so the
live resource count plateaus instead of climbing to the ceiling.

Provider-only change. The libs/mlx-swift* submodules are untouched.

Target: 0.6.12.

Root cause (verified)

Gemma-4 is heterogeneous (sliding [8,256] + full [2,512]), so it uses the
.checkpoint prefix-cache tier, which is on by default (opt out with
DARKBLOOM_PREFIX_CACHE=0):

  • provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:1029-1066 — .checkpoint tier setup
  • provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:1185-1188 — prefix cache default-ON / opt-out

The capture hook, fired per checkpoint boundary, spawned an unbounded
detached Task:

  • provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:1115-1124 (production) and :821-825 (test seam)
scheduler.onCheckpointCapture = { prefixTokens, length, caches in
    let box = SendableKVCaches(caches)
    Task { await mgr.store(tokens: prefixTokens, checkpointLength: length, caches: box) }  // <-- UNBOUNDED
}

The hook is fired synchronously on the engine queue with a freshly-extracted,
per-layer KV snapshot:

  • libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatching/Scheduler.swift:396-401 — caches = pp.ppBatch.promptCache.map { $0.extractBatched(0) }

Each spawned Task pins a full per-layer KV snapshot (live MLXArrays,
≈ layers × 2 Metal buffers) until mgr.store runs
. PrefixCacheManager is a
single actor that serializes store behind AES-GCM serialize + fsync and
against every lookup/materialize:

  • provider-swift/Sources/ProviderCore/KVCache/PrefixCacheManager.swift:752 — func store(...)

Under sustained traffic the actor falls behind, the capture Tasks queue, their
live snapshots accumulate, and the live Metal resource COUNT (independent of
bytes — see Memory.numResources / Memory.resourceLimit in
libs/mlx-swift/Source/MLX/Memory.swift:199-222) climbs to the
iogpu.rsrc_limit ceiling (~499000) → crash.

Why the prior mlx/mlx-c "count-aware" fixes can't fix this

Those fixes trim the cache (recycled, freed buffers) by making the trim
count-aware. But the snapshots held by the queued capture Tasks are LIVE,
not cached — they are still referenced, so the allocator cannot reclaim them no
matter how aggressively the cache is trimmed. The idle-gated
Memory.clearCache() also never fires under sustained load. The only fix is to
bound the number of live snapshots retained in flight, which is what this PR
does.

The fix (provider-only)

  1. Backpressure / bounded capture pipeline (primary). New
    CheckpointCapturePipeline (BatchScheduler.swift → new
    CheckpointCapturePipeline.swift): a bounded, single-consumer AsyncStream
    (bufferingNewest(max-in-flight)) feeding one consumer Task that calls
    mgr.store. submit is synchronous/non-blocking and drops the surplus
    snapshot on full
    (released immediately, so its Metal buffers free). This
    caps retained live snapshots to a small constant — max-in-flight + 1
    (buffer + the one in the consumer) — regardless of how far behind the
    manager actor falls. Default max-in-flight = 2, env-tunable via
    DARKBLOOM_KV_CAPTURE_MAX_INFLIGHT. Dropping is safe: capture is best-effort
    cache-warming, so a drop only costs a future cache miss, never correctness.

  2. Admission gate under resource pressure (secondary, cheap). Before
    enqueuing, skip capture when the live Metal resource count is high —
    Memory.numResources > 0.7 × Memory.resourceLimit (guards
    resourceLimit == 0). This stops feeding the leak exactly when it matters,
    and matches the engine's existing [rsrc] 70%-pressure threshold.

  3. Teardown drains/cancels. stopCurrentEngine (and the superseded-load
    bailouts) finish the stream and cancel the consumer, releasing any retained
    snapshots so nothing leaks across model swaps. Ordered before the manager
    flush so an in-flight store can't race the index flush / accountant
    deregister.

The decode path, KV-cache classes, and the manager's persistence logic are
unchanged; the only behavior change is bounding capture. Both capture-hook
sites (production builder + test seam) share one makeCheckpointCaptureWiring
helper.

Tests

swift build passes; new + existing suites are green against master
(v0.6.11) submodule pins:

  • New CheckpointCapturePipelineTests (4 tests):
    • capturePipelineBoundsInFlightSnapshots — floods the pipeline against a
      deliberately-stalled consumer and asserts the number of retained snapshots
      never exceeds the small constant bound (vs all N if unbounded), that
      overflow is dropped not queued, and that nothing leaks after drain.
    • capturePipelineCapacityFloorIsOne — capacity clamps to ≥ 1.
    • captureAdmissionGateThreshold — 70% threshold math incl. the
      resourceLimit == 0 guard.
    • captureMaxInFlightIsSmallAndPositive — default cap + env knob.
  • Regression suites: BatchScheduler, PrefixCache, Continuous, Hybrid,
    KVCache — 226 tests pass (live model-download tests skip without
    DARKBLOOM_LIVE_MLX_TESTS=1).

Validating in prod

Run a provider on Gemma-4 with the resource-count diagnostic (default-on; this
just makes the cadence explicit):

DARKBLOOM_MLX_RESOURCE_DEBUG=1 darkbloom serve

Watch the [rsrc] log line (subsystem dev.darkbloom.provider, category
rsrc). Before this change the live resources count climbs monotonically
toward 499000 under sustained traffic; after it should plateau well below
the limit. Optionally tune DARKBLOOM_KV_CAPTURE_MAX_INFLIGHT (default 2).


View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.

…e-resource (499000) leak

Heterogeneous models (Gemma-4) use the `.checkpoint` prefix-cache tier. The
capture hook spawned an UNBOUNDED `Task { await mgr.store(...) }` per
checkpoint boundary, each pinning a live per-layer KV snapshot (≈ layers × 2
Metal buffers) until the single `PrefixCacheManager` actor — serialized behind
AES-GCM + fsync and against every lookup/materialize — ran it. Under sustained
traffic the actor falls behind, the detached Tasks queue, their live snapshots
accumulate, and the live Metal buffer COUNT (not bytes/cache) climbs to the
`iogpu.rsrc_limit` ceiling (~499000) → `[metal::malloc] Resource limit
exceeded` crash. The mlx/mlx-c count-aware cache trims cannot help: these
buffers are LIVE, not cached, and the idle-gated `Memory.clearCache()` never
fires under load.

Bound the live snapshots in flight instead:

- CheckpointCapturePipeline — a bounded, single-consumer AsyncStream
  (`bufferingNewest(max-in-flight)`, default 2, env-tunable via
  DARKBLOOM_KV_CAPTURE_MAX_INFLIGHT) that drops the surplus snapshot on full
  and releases it. Capture is best-effort cache-warming, so a drop only costs
  a future cache miss, never correctness. This caps retained live snapshots to
  a small constant regardless of how far behind the manager falls.
- Admission gate — skip capture when the live MLX resource count exceeds 70%
  of `Memory.resourceLimit` (guards `resourceLimit == 0`), so we stop feeding
  the leak exactly when it matters.
- Teardown — `stopCurrentEngine` (and the superseded-load bailouts) now drain
  and cancel the pipeline, releasing any retained snapshots so nothing leaks
  across model swaps.

The decode path, KV-cache classes, and the manager's persistence logic are
unchanged; the only behavior change is bounding capture. Adds a focused unit
test proving the in-flight bound holds and overflow is dropped, not queued.
@vercel

vercel Bot commented Jun 16, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview Jun 16, 2026 10:12pm
d-inference-console-ui-dev Ready Ready Preview Jun 16, 2026 10:12pm
d-inference-landing Ready Ready Preview Jun 16, 2026 10:12pm

Request Review

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated Code Review — Layr-Labs/d-inference#

Verdict: REQUEST_CHANGES

Security — ✅ No issues found

Performance — 4 finding(s) (3 blocking)

  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:61 — NSLock allocation on every pipeline instance for lightweight counters
    • Suggestion: Consider using atomic operations (OSAtomicIncrement32 or std::atomic equivalent) for simple counters instead of NSLock to reduce allocation overhead
  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:120-122 — Lock acquisition in getter methods called from hot paths
    • Suggestion: Cache counter values or use lock-free atomic operations since these are simple integer counters accessed frequently
  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:258 — Redundant pipeline shutdown calls in multiple cleanup paths
    • Suggestion: Add a shutdown flag to make shutdown() idempotent and avoid redundant work in cleanup paths
  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:218 — captureResourcePressureHigh() called on every checkpoint capture
    • Suggestion: Cache the resource pressure check result for a short duration (e.g., 100ms) since MLX.Memory counters don't change rapidly

Type_diligence — ✅ No issues found

Additive_complexity — 4 finding(s) (1 blocking)

  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:258 — Identical cleanup pattern repeated 4 times with same identity checks
    • Suggestion: Extract a helper method cleanupBuildArtifacts(build:) to eliminate the repeated identity-checked cleanup pattern
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:61 — Generic pipeline class when only one concrete type is used
    • Suggestion: Consider making this concrete for CheckpointCapture since no other payload types are anticipated
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:69-71 — Lock-guarded counters for simple statistics that could be atomic
    • Suggestion: Use OSAtomicIncrement64 or similar atomic operations instead of NSLock for simple counters
  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:1185-1188 — Complex capture pipeline construction logic embedded in engine builder
    • Suggestion: Move the capture pipeline factory logic to a dedicated builder class or the CheckpointCapturePipeline itself

8 finding(s) total, 4 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

/// fixes the 499000 leak.
///
/// Generic over `Payload` so the bounding/drop/teardown logic is unit-testable
/// without MLX (the production instantiation is `Payload == CheckpointCapture`).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] ⚡ NSLock allocation on every pipeline instance for lightweight counters

💡 Suggestion: Consider using atomic operations (OSAtomicIncrement32 or std::atomic equivalent) for simple counters instead of NSLock to reduce allocation overhead

📊 Score: 2×3 = 6 · Category: Unbounded allocations

@@ -251,6 +258,7 @@ public actor BatchScheduler {
if self.checkpointBoundaries == build.checkpointBoundaries { self.checkpointBoundaries = [] }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] ⚡ Redundant pipeline shutdown calls in multiple cleanup paths

💡 Suggestion: Add a shutdown flag to make shutdown() idempotent and avoid redundant work in cleanup paths

📊 Score: 3×3 = 9 · Category: Repeated work

"checkpoint capture pipeline: max-in-flight \(maxInFlight) (drop-on-full), admission-gate at \(Int(captureResourcePressureFraction * 100))% of Metal resource limit")
let hook: CheckpointCaptureHook = { [pipeline] prefixTokens, length, caches in
// 1. Admission gate. Returning here lets the `caches` argument go
// out of scope → its Metal buffers free immediately.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] ⚡ captureResourcePressureHigh() called on every checkpoint capture

💡 Suggestion: Cache the resource pressure check result for a short duration (e.g., 100ms) since MLX.Memory counters don't change rapidly

📊 Score: 2×4 = 8 · Category: Repeated work

@@ -251,6 +258,7 @@ public actor BatchScheduler {
if self.checkpointBoundaries == build.checkpointBoundaries { self.checkpointBoundaries = [] }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🧩 Identical cleanup pattern repeated 4 times with same identity checks

💡 Suggestion: Extract a helper method cleanupBuildArtifacts(build:) to eliminate the repeated identity-checked cleanup pattern

📊 Score: 2×3 = 6 · Category: duplicate logic

/// fixes the 499000 leak.
///
/// Generic over `Payload` so the bounding/drop/teardown logic is unit-testable
/// without MLX (the production instantiation is `Payload == CheckpointCapture`).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🧩 Generic pipeline class when only one concrete type is used

💡 Suggestion: Consider making this concrete for CheckpointCapture since no other payload types are anticipated

📊 Score: 2×2 = 4 · Category: over-abstraction

Comment on lines +69 to +71
// Lightweight counters (lock-guarded; read from tests / future telemetry).
private let statsLock = NSLock()
private var _accepted = 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🧩 Lock-guarded counters for simple statistics that could be atomic

💡 Suggestion: Use OSAtomicIncrement64 or similar atomic operations instead of NSLock for simple counters

📊 Score: 1×2 = 2 · Category: over-configuration

@github-actions

github-actions Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

This PR fixes a Metal resource exhaustion crash (the "Gemma-4 499000 leak") by replacing an unbounded Task-per-checkpoint dispatch with a bounded, drop-on-overflow pipeline; it has no negative security posture impact and makes one minor positive contribution to T-028/T-041.


Trust Boundaries Touched

  • TB-003 (Provider operator vs. process) — changes to inference buffer lifecycle
  • TB-007 (Provider inference engine) — changes to KV snapshot handling and teardown sequencing

Threat Assessment

T-007 — Provider serves manipulated model outputs (BatchScheduler.swift, CheckpointCapturePipeline.swift)
ℹ️ Neutral. The new pipeline does not change which checkpoint data is written or how weight integrity is verified. The fail-open weight-hash enforcement (SEC-007) is unchanged.

T-028 — Residual inference data in GPU memory after request completes (BatchScheduler.swift lines ~258, ~302, ~342, ~1944–1950)
✅ Minor strengthening. The explicit capturePipeline?.shutdown(); capturePipeline = nil calls at every engine teardown path — including the three identity-checked early-exit branches and stopCurrentEngine — ensure that live KV snapshots (which are live Metal buffers containing inference data) are released deterministically rather than lingering until the unbounded Task queue drains. This closes a gap where prior prompt content could persist in GPU-backed MLX arrays beyond the intended lifetime of the inference session. The broader open finding (GPU buffers not explicitly zeroed between requests) remains; this PR only fixes the lifetime bound, not the zeroing gap.

T-041 — Cross-tenant prefix-cache sharing + TTFT timing oracle (BatchScheduler.swift, CheckpointCapturePipeline.swift)
ℹ️ Neutral on the cross-tenant sharing/timing oracle (SEC-035 remains open). The new pipeline does not change whether the cache is shared across tenants or what metadata is written in plaintext AAD. The fix does, however, bound the number of simultaneously live KV snapshots, which incidentally reduces the window during which a given consumer's decrypted prefix tokens occupy GPU memory beyond their request lifetime — but this is a side effect, not a targeted mitigation.


New Attack Surface

Drop-on-overflow is silent to the consumer. CheckpointCapturePipeline.submit() returns Bool and increments _droppedCount, but the call sites in makeCheckpointCaptureWiring (BatchScheduler.swift) use @discardableResult — the return value is discarded. A sustained drop storm (e.g. an adversarial consumer who submits requests at exactly the checkpoint cadence to keep the pipeline saturated) causes cache misses that are invisible at the coordinator level. This is explicitly accepted in the design ("Dropping a snapshot only costs a future cache miss, never correctness"), and has no correctness or confidentiality impact. However, the _droppedCount / _acceptedCount stats are only accessible via the acceptedCount / droppedCount properties with no upstream telemetry path visible in this diff. If drop rates are never surfaced, sustained degradation of the prefix cache (which is a privacy-relevant feature per T-041) will be silent in production telemetry.

This is not covered by an existing threat. Recommend adding a telemetry emission (heartbeat or metrics counter) for droppedCount so operators can detect when the bounded pipeline is chronically saturated and cache effectiveness collapses — particularly relevant before a multi-tenant deployment where the cache must be audited per SEC-035.


Open Findings Resolved

None of the tracked SEC-* findings are resolved by this PR. SEC-007, SEC-016, SEC-017, SEC-035 remain open and are untouched.


Summary of Concerns (Priority Order)

# File Lines Concern Severity
1 CheckpointCapturePipeline.swift ~145–155 droppedCount has no upstream emission path; sustained drop storms are invisible in production Low
2 BatchScheduler.swift ~258, ~302, ~342 Shutdown in early-exit branches calls shutdown() and nils the pipeline but does not await waitUntilDrained(); if an in-flight mgr.store is mid-fsync at teardown the next engine build could begin while the old crypto+fsync path is still running against the shared PrefixCacheManager. The consumer.cancel() in shutdown() handles this via cooperative cancellation, but the comment in CheckpointCapturePipeline acknowledges the consumer does continue rather than break on cancellation — meaning in-flight stores are abandoned but not awaited. Confirm this is safe with respect to the index flush that follows capturePipeline = nil in stopCurrentEngine. Low

🔐 Threat model: docs/threat-model.yaml · Updates on each push to this PR

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e593383fad

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +91 to +92
for await payload in stream {
await consume(payload)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor cancellation before draining buffered captures

When a model is unloaded while this stream has buffered captures, shutdown() calls finish() and cancel(), but this loop never observes cancellation. AsyncStream continues yielding values that were already buffered after finish/cancel, so a backlogged consumer can keep holding and storing old-model KV snapshots after stopCurrentEngine has moved on to flush/deregister or load the next engine. That defeats the teardown guarantee and can overlap large Metal buffers across a model swap; break on Task.isCancelled before consuming buffered values, or explicitly discard the queue, so shutdown actually drops them.

Useful? React with 👍 / 👎.

@blacksmith-sh

blacksmith-sh Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

Found 1 test failure on Blacksmith runners:

Failure

Test View Logs
github.com/eigeninference/d-inference/e2e/TestIntegration_ConcurrentRequests View Logs

Fix with Codesmith
Need help on this PR? Tag /codesmith with what you need.

…ion)

CheckpointCapturePipeline.shutdown() calls finish() + cancel(), but an
AsyncStream for-await loop does not observe Task cancellation on its own and
finish() still delivers already-buffered payloads. The consumer therefore kept
store()-ing buffered KV snapshots after a model swap had begun, pinning live
Metal buffers across engines — the exact overlap teardown was meant to prevent.

Honor cancellation inside the loop: once cancelled, keep pulling the buffered
remainder (so the retained continuation does not strand it alive) but skip
consume(), dropping the best-effort captures. Add a regression test proving only
the in-flight capture runs after shutdown and nothing leaks.
@Gajesh2007

Copy link
Copy Markdown
Member Author

Addressed the cancellation/teardown review point in a776a51: shutdown() already called finish() + cancel(), but an AsyncStream for await doesn't observe Task cancellation on its own and finish() still delivers buffered payloads — so the consumer could still store(...) old-model KV snapshots after a model swap began. The loop now checks Task.isCancelled and drain-and-drops the buffered remainder (keeps pulling so the retained continuation doesn't strand it alive, but skips consume). Added a regression test (capturePipelineDropsBufferedCapturesOnShutdown) proving only the in-flight capture runs after shutdown and nothing leaks; full capturePipeline suite green.

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated Code Review — Layr-Labs/d-inference#

Verdict: REQUEST_CHANGES

Security — ✅ No issues found

Performance — 3 finding(s) (1 blocking)

  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:86-89 — AsyncStream with bufferingNewest policy may cause memory pressure under high load
    • Suggestion: Consider adding telemetry to monitor buffer utilization and dropped payloads to validate the capacity sizing in production
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:70-72 — NSLock usage in stats tracking could cause contention on high-frequency submit calls
    • Suggestion: Replace NSLock with atomic operations (OSAtomicIncrement64 or similar) for simple counters to eliminate lock contention
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:1945-1952 — Synchronous shutdown and drain operations in stopCurrentEngine may block actor
    • Suggestion: Consider making capturePipeline shutdown asynchronous or use a detached task to avoid blocking the actor during engine teardown

Type_diligence — ✅ No issues found

Additive_complexity — 4 finding(s)

  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:258 — Identical cleanup pattern repeated 4 times with same identity checks
    • Suggestion: Extract a helper method cleanupBuildArtifacts(build:) to eliminate the repeated identity-check cleanup pattern
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:61 — Generic type parameter adds complexity for single concrete use
    • Suggestion: Remove generic <Payload: Sendable> and hardcode CheckpointCapture since there's only one production use case
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:70-72 — Lightweight counters with lock for simple integers
    • Suggestion: Use atomic operations or remove counters entirely if only used for testing
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:158-162 — Environment variable tuning for internal buffer size
    • Suggestion: Remove env var tuning - the default of 2 is already conservative and this adds unnecessary configuration surface

7 finding(s) total, 1 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment on lines +86 to +89
of: Payload.self,
bufferingPolicy: .bufferingNewest(cap)
)
self.continuation = continuation

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] ⚡ AsyncStream with bufferingNewest policy may cause memory pressure under high load

💡 Suggestion: Consider adding telemetry to monitor buffer utilization and dropped payloads to validate the capacity sizing in production

📊 Score: 3×4 = 12 · Category: Unbounded allocations

Comment on lines +70 to +72
private let statsLock = NSLock()
private var _accepted = 0
private var _dropped = 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] ⚡ NSLock usage in stats tracking could cause contention on high-frequency submit calls

💡 Suggestion: Replace NSLock with atomic operations (OSAtomicIncrement64 or similar) for simple counters to eliminate lock contention

📊 Score: 2×3 = 6 · Category: Blocking I/O on hot paths

Comment on lines 1945 to +1952
modelContainer = nil
tokenizer = nil
// Drain the bounded capture pipeline: the engine is stopped (no more
// capture hooks fire), so finish the stream and cancel the consumer.
// This releases any retained KV snapshots and stops an in-flight
// `mgr.store` from racing the index flush / accountant deregister below,
// and guarantees no snapshot (or consumer Task) leaks across a swap.
capturePipeline?.shutdown()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] ⚡ Synchronous shutdown and drain operations in stopCurrentEngine may block actor

💡 Suggestion: Consider making capturePipeline shutdown asynchronous or use a detached task to avoid blocking the actor during engine teardown

📊 Score: 2×2 = 4 · Category: Blocking I/O on hot paths

@@ -251,6 +258,7 @@ public actor BatchScheduler {
if self.checkpointBoundaries == build.checkpointBoundaries { self.checkpointBoundaries = [] }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🧩 Identical cleanup pattern repeated 4 times with same identity checks

💡 Suggestion: Extract a helper method cleanupBuildArtifacts(build:) to eliminate the repeated identity-check cleanup pattern

📊 Score: 2×3 = 6 · Category: duplicate logic

/// fixes the 499000 leak.
///
/// Generic over `Payload` so the bounding/drop/teardown logic is unit-testable
/// without MLX (the production instantiation is `Payload == CheckpointCapture`).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🧩 Generic type parameter adds complexity for single concrete use

💡 Suggestion: Remove generic <Payload: Sendable> and hardcode CheckpointCapture since there's only one production use case

📊 Score: 2×2 = 4 · Category: over-configuration

Comment on lines +70 to +72
private let statsLock = NSLock()
private var _accepted = 0
private var _dropped = 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🧩 Lightweight counters with lock for simple integers

💡 Suggestion: Use atomic operations or remove counters entirely if only used for testing

📊 Score: 1×2 = 2 · Category: over-abstraction

Comment on lines +158 to +162
// make sure the stream terminates and the consumer Task ends.
continuation.finish()
consumer.cancel()
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🧩 Environment variable tuning for internal buffer size

💡 Suggestion: Remove env var tuning - the default of 2 is already conservative and this adds unnecessary configuration surface

📊 Score: 1×2 = 2 · Category: over-configuration

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated Code Review — Layr-Labs/d-inference#

Verdict: REQUEST_CHANGES

Security — ✅ No issues found

Performance — 3 finding(s) (1 blocking)

  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:86-89 — AsyncStream with bufferingNewest policy may still accumulate tasks under high contention
    • Suggestion: Consider adding explicit task cancellation tracking or using a semaphore-based approach to guarantee bounded concurrency
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:95-110 — Consumer task processes payloads serially which could create backpressure
    • Suggestion: Consider parallel processing of payloads if the consume function is I/O bound, or document that this is intentionally serial
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:1948-1952 — Shutdown called multiple times in different code paths without idempotency check
    • Suggestion: Add explicit idempotency check in shutdown() method or ensure callers coordinate to avoid redundant shutdown calls

Type_diligence — ✅ No issues found

Additive_complexity — 5 finding(s) (1 blocking)

  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:61 — Generic pipeline class when only one concrete type is used
    • Suggestion: Consider making this non-generic since it's only used with CheckpointCapture. The generic abstraction adds complexity without clear benefit.
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:70-72 — Lightweight counters with manual locking for simple statistics
    • Suggestion: Consider using atomic operations or removing these counters entirely if they're only for testing/debugging. The manual locking adds complexity for simple increment operations.
  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:258 — Identical cleanup pattern repeated 4 times in the file
    • Suggestion: Extract the identity-checked cleanup pattern into a helper method to reduce duplication and maintenance burden.
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:156-162 — Environment variable parsing with fallback for simple integer
    • Suggestion: Consider using a simpler approach or removing the environment variable entirely since this is an internal tuning parameter with a reasonable default.
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:95-108 — Task cancellation check in data processing loop
    • Suggestion: Consider handling cancellation at the Task level rather than checking it inside the processing loop, which mixes cancellation concerns with data processing logic.

8 finding(s) total, 2 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment on lines +86 to +89
of: Payload.self,
bufferingPolicy: .bufferingNewest(cap)
)
self.continuation = continuation

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] ⚡ AsyncStream with bufferingNewest policy may still accumulate tasks under high contention

💡 Suggestion: Consider adding explicit task cancellation tracking or using a semaphore-based approach to guarantee bounded concurrency

📊 Score: 3×4 = 12 · Category: Unbounded goroutines

Comment on lines +95 to +110
// `for await` does NOT observe Task cancellation on its own.
// Without this guard we would `store(...)` old-model KV
// snapshots after a model swap has begun — pinning large live
// Metal buffers that must not overlap the next engine.
//
// We `continue` rather than `break`: the buffered remainder must
// still be pulled so each payload is released as it drains (the
// retained `continuation` keeps the stream's internal buffer —
// and anything stranded in it — alive). Skipping `consume` drops
// the captures (best-effort) without storing them; the finished
// stream then terminates the loop once its buffer empties.
if Task.isCancelled { continue }
await consume(payload)
}
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] ⚡ Consumer task processes payloads serially which could create backpressure

💡 Suggestion: Consider parallel processing of payloads if the consume function is I/O bound, or document that this is intentionally serial

📊 Score: 2×3 = 6 · Category: Blocking I/O on hot paths

Comment on lines +1948 to +1952
// capture hooks fire), so finish the stream and cancel the consumer.
// This releases any retained KV snapshots and stops an in-flight
// `mgr.store` from racing the index flush / accountant deregister below,
// and guarantees no snapshot (or consumer Task) leaks across a swap.
capturePipeline?.shutdown()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] ⚡ Shutdown called multiple times in different code paths without idempotency check

💡 Suggestion: Add explicit idempotency check in shutdown() method or ensure callers coordinate to avoid redundant shutdown calls

📊 Score: 2×2 = 4 · Category: Repeated work

/// fixes the 499000 leak.
///
/// Generic over `Payload` so the bounding/drop/teardown logic is unit-testable
/// without MLX (the production instantiation is `Payload == CheckpointCapture`).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🧩 Generic pipeline class when only one concrete type is used

💡 Suggestion: Consider making this non-generic since it's only used with CheckpointCapture. The generic abstraction adds complexity without clear benefit.

📊 Score: 2×3 = 6 · Category: over-abstraction

Comment on lines +70 to +72
private let statsLock = NSLock()
private var _accepted = 0
private var _dropped = 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🧩 Lightweight counters with manual locking for simple statistics

💡 Suggestion: Consider using atomic operations or removing these counters entirely if they're only for testing/debugging. The manual locking adds complexity for simple increment operations.

📊 Score: 2×2 = 4 · Category: over-configuration

@@ -251,6 +258,7 @@ public actor BatchScheduler {
if self.checkpointBoundaries == build.checkpointBoundaries { self.checkpointBoundaries = [] }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] 🧩 Identical cleanup pattern repeated 4 times in the file

💡 Suggestion: Extract the identity-checked cleanup pattern into a helper method to reduce duplication and maintenance burden.

📊 Score: 3×4 = 12 · Category: duplicate logic

Comment on lines +156 to +162
deinit {
// Belt-and-suspenders: if the owner dropped us without `shutdown()`,
// make sure the stream terminates and the consumer Task ends.
continuation.finish()
consumer.cancel()
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🧩 Environment variable parsing with fallback for simple integer

💡 Suggestion: Consider using a simpler approach or removing the environment variable entirely since this is an internal tuning parameter with a reasonable default.

📊 Score: 2×2 = 4 · Category: over-configuration

Comment on lines +95 to +108
// `for await` does NOT observe Task cancellation on its own.
// Without this guard we would `store(...)` old-model KV
// snapshots after a model swap has begun — pinning large live
// Metal buffers that must not overlap the next engine.
//
// We `continue` rather than `break`: the buffered remainder must
// still be pulled so each payload is released as it drains (the
// retained `continuation` keeps the stream's internal buffer —
// and anything stranded in it — alive). Skipping `consume` drops
// the captures (best-effort) without storing them; the finished
// stream then terminates the loop once its buffer empties.
if Task.isCancelled { continue }
await consume(payload)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🧩 Task cancellation check in data processing loop

💡 Suggestion: Consider handling cancellation at the Task level rather than checking it inside the processing loop, which mixes cancellation concerns with data processing logic.

📊 Score: 2×3 = 6 · Category: misplaced responsibility

Gajesh2007 added a commit that referenced this pull request Jun 16, 2026
Memory & reliability hardening:
- 90% unified-memory cap + KV purge on unload + serve-while-load reservation (#363)
- bounded checkpoint-capture pipeline, stops the Metal 499000 resource leak (#374)
- resumable 4-bit model downloads + restart-safe detection (#372)
- default-on [rsrc] resource telemetry in reports (#373 / mlx-swift-lm#42)
- don't log raw request-parse errors — prompt-fragment privacy (#376)

Coordinator LatestProviderVersion bump is intentionally deferred until the signed
0.6.12 bundle is published (prod uses the in-memory store, so the hardcoded
fallback is authoritative after a redeploy).

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference-console-ui-dev — d9623adf Deployed Jun 16, 2026 by vercel[bot]
Preview – d-inference — d9623adf Deployed Jun 16, 2026 by vercel[bot]
Preview – d-inference-landing — d9623adf Deployed Jun 16, 2026 by vercel[bot]
benchmarks — d9623adf Deployed Jun 16, 2026 by Gajesh2007 via E2E Benchmarks #1053
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants